class DownloadExcel {
    constructor(options) {
        this.downloadExcel(options);
    }
    downloadExcel(options) {
        let { titleOrder, tableData, name } = options;

        let fileName = name;

        let headerData = titleOrder.map((title) => `<th>${title}</th>`).join("");
        let rowData = `<tr>${headerData}</tr>`;

        let rowBody = tableData
            .map((tr) => {
                let bodyData = titleOrder
                    .map((title) => {
                        return `<td>${tr[title]}</td>`;
                    })
                    .join("");
                let trContainer = `<tr>${bodyData}</tr>`;
                return trContainer;
            })
            .join("");
        let excel = `<table>${rowData}${rowBody}</table>`;
        this.table2Download(excel, fileName);
    }
    table2Download(excel, fileName) {
        let excelFile = `
            <html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>
                <meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">
                <head>
                    <!--[if gte mso 9]>
                        <xml>
                        <x:ExcelWorkbook>
                        <x:ExcelWorksheets>
                        <x:ExcelWorksheet>
                        <x:Name>
                        {worksheet}
                        </x:Name>
                        <x:WorksheetOptions>
                        <x:DisplayGridlines/>
                        </x:WorksheetOptions>
                        </x:ExcelWorksheet>
                        </x:ExcelWorksheets>
                        </x:ExcelWorkbook>
                        </xml>
                    <![endif]-->
                </head>
                <body>
                    ${excel}
                </body>
            </html>
        `;
        let uri = "data:application/vnd.ms-excel;charset=utf-8," + encodeURIComponent(excelFile);
        let link = document.createElement("a");
        link.href = uri;
        link.style = "visibility:hidden";
        link.download = fileName + ".xls";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
}
